<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="icon" href="static/images/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="static/images/favicon.ico"
	type="image/x-icon" />
<link rel="bookmark" href="static/images/favicon.ico"
	type="image/x-icon" />
<script src="static/js/jquery-3.3.1.js" type="text/javascript"></script>
<script src="static/js/jsencrypt.js" type="text/javascript"></script>
<script type='text/javascript' src='/dwr/interface/rsaUtils'></script>
<script type='text/javascript' src='/dwr/engine.js'></script>
</head>
<body>
	<form action="/login" method="post" name="formLogin">
		用户名：<input type="text" name="username" id="username"><br />
		密码：<input type="password" name="password" id="password"><br />
		登录：<input type="button" id="login" value="登录">
		<!-- 登录：<input type = "submit"  value="登录" onClick="return validateLogin()" /> -->
	</form>
	<button onclick="test()">获得公钥</button>
</body>

<script>
	publicKey = null;
	encodedpass = null;
	//页面加载获取public key,测试时每个账号获取一对公私钥，实际可一个ip对应一对秘钥
	$.ajax({
		url : "/generateRSAKey",
		type : "post",
		data : "Bruce",
		dataType : "text",
		success : function(data) {
			publicKey = data;
			if (publicKey == null) {
				$("#msg").html("获取publicKey失败，请联系管理员！");
				$("#login-btn").removeAttr("disabled");
			}
		}

	});

	//根据公钥加密密码
	function callBack(data) {
		encodedpass = data;
		alert("加密后的密码" + encodedpass);
	}
	function get(pstring) {
		return rsaUtils.publicEncrypt(pstring, publicKey, callBack);
	}

	//进行RSA加密
	/* 	var encrypt = new JSEncrypt();
	 encrypt.setPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCp0wHYbg/NOPO3nzMD3dndwS0MccuMeXCHgVlGOoYyFwLdS24Im2e7YyhB0wrUsyYf0/nhzCzBK8ZC9eCWqd0aHbdgOQT6CuFQBMjbyGYvlVYU2ZP7kG9Ft6YV6oc9ambuO7nPZh+bvXH0zDKfi02prknrScAKC0XhadTHT3Al0QIDAQAB");
	 var username = encrypt.encrypt(pstring);
	 var password =encrypt.encrypt(pstring);  */
</script>

<script>
	//$.trim删除字符串开头和末尾的空格
	$("#login").click(function() {
		var pstring = $.trim($("#password").val());
		var username = $.trim($("#username").val());
		$.ajax({
			url : "/login",
			type : "post",
			data : {
				username : username,
				password : encodedpass,
				method : "login"
			},
			dataType : "json",
			resurtType : "json",
			beforeSend : function(pstring) {
				/* encodedpass = get(pstring); */
			},

			success : function(result, textStatus, jqXHR) {
				//返回的不是json需要转换成json
				/* var ret = JSON.parse(result); */
				if (1 == result.ret) {
					var name = result.data.username;
					window.location.href = "/welcome.html?name=" + name;
				} else {
					alert("登录失败！");
				}
			}
		});
	});
</script>

</html>